//
//  HomeViewController.m
//  HAODE
//
//  Created by LiYinDi on 15/12/22.
//  Copyright © 2015年 reabam.com. All rights reserved.
//

#import "HomeViewController.h"
#import "JKSideSlipView.h"
#import "MenuView.h"
#import <objc/runtime.h>
#import <RongIMKit/RongIMKit.h>
#import "MessageViewController.h"
#import "RDVTabBarController.h"
#import "TheLoginViewController.h"
#import "GenerateQRCodeViewController.h"
#import "UIButton+UIButtonImageAndText.h"
#import "ToBindCompanyViewController.h"
#import "ReabamSingleton.h"
@interface HomeViewController ()<JKSideSlipViewDelegate,MenuViewDelegate,RCIMUserInfoDataSource,UIGestureRecognizerDelegate, RCIMConnectionStatusDelegate,
    RCIMReceiveMessageDelegate>
{
    JKSideSlipView *_sideSlipView;
    NSArray *textArray;
    NSArray *imageArray;
    NSArray *colorArray;
    NSMutableArray *selectedTextArray;
    NSMutableArray *selectedImageArray;
    NSArray *defaultTextArray;
    NSArray *defaultImageArray;
    NSArray *viewControllerArray;
    BOOL isDefault;
    BOOL sliderIsOpen;
    ReabamSingleton*commdity;
    NSDictionary *plistDictionary;
}
@end

@implementation HomeViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.title = @"经营";
    }
    return self;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    //
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* CFBundleVersion = [user objectForKey:@"CFBundleVersion"];
    if ([[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]isEqualToString:CFBundleVersion]) {
    }else{
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]  forKey:@"CFBundleVersion"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"parent0"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"parent1"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"parent2"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"parent3"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"parent4"];
        [user synchronize];
    }
    [self NewVersion];
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 93)];
    [view setBackgroundColor:[UIColor clearColor]];
    UIVisualEffect *blurEffect;
    blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    UIVisualEffectView *frostedView;
    frostedView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    frostedView.frame = view.bounds;
    [view addSubview:frostedView];
    [_contentView addSubview:view];
    [_contentView bringSubviewToFront:_topView];
    [_topView setBackgroundColor:[UIColor clearColor]];
    self.automaticallyAdjustsScrollViewInsets=NO;
    // Do any additional setup after loading the view from its nib.
    _dotLabel.layer.cornerRadius=4;
    _dotLabel.layer.masksToBounds=YES;

   
    [self menuView];
}

-(void)menuView{
    isDefault=YES;
    sliderIsOpen=NO;
    [_sideSlipView removeFromSuperview];
    _sideSlipView = [[JKSideSlipView alloc]initWithSender:self];
    _sideSlipView.delegate=self;
    _sideSlipView.backgroundColor = [UIColor whiteColor];
    MenuView *menu = [MenuView menuView];
    menu.delegate=self;
    [menu didSelectRowAtIndexPath:^(id cell, NSIndexPath *indexPath) {
        [_sideSlipView hide];
        
    }];
    [_leftSliderBtn setImage:[UIImage imageNamed:@"jingying_new.png"] forState:UIControlStateNormal];
    
    
    viewControllerArray=[NSArray arrayWithObjects:@"GenerateQRCodeViewController",@"MemberListViewController",@"NewMediaPromotionViewController",@"CashierNewViewController", @"OrderListViewController", @"DeliverylistViewController", @"RefundListViewController", @"NeedOrderListViewController",@"WhsInListViewController",@"WhsOutListViewController",@"CheckVouchListViewController",@"StockManagementViewController",@"AllotOrderListViewController",@"GoodsInOrderListViewController",@"BookingOrderViewController", nil];
    selectedTextArray=[NSMutableArray array];
    selectedImageArray=[NSMutableArray array];
    defaultTextArray=[NSArray arrayWithObjects:@"扫码入会",@"会员管理", @"下单收银",@"销售订单",@"提货配送",@"要货订单",@"商品入库",@"商品出库",nil];
    defaultImageArray=[NSArray arrayWithObjects:@"dianpuerweima", @"huiyuan",
                       
                       @"shouyin",
                       @"xiaoshoudingdan",
                       @"tihuopeisong",
                       @"yaohuoguanli",
                       @"shangpinruku",
                       @"shangpinchuku", nil];
    menu.items = @[@{@"title":@"营销管理" },@{@"title":@"销售管理" },@{@"title":@"库存管理"}];
    textArray=[NSArray arrayWithObjects:@"扫码入会", @"会员管理",@"新媒体推广",@"下单收银",@"销售订单",@"提货配送",@"销售退货",@"要货订单",@"商品入库",@"商品出库",@"库存盘点",@"存货管理",@"调拨单",@"进货单",nil];
    
    imageArray=[NSArray arrayWithObjects: @"dianpuerweima",
                
                @"huiyuan",
                @"xinmeitituiguang",
                @"shouyin",
                @"xiaoshoudingdan",
                @"tihuopeisong",
                @"xiaoshoutuihuo_new",
                @"yaohuoguanli",
                @"shangpinruku",
                @"shangpinchuku",
                @"kucunpandian",
                @"cunhuoguanli",
                @"diaobodan",
                @"jinhuodan",
                 nil];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSMutableArray* funConfigs = [user objectForKey:@"funConfigs"];
    
    NSLog(@"=========%@",funConfigs);
    
    if (funConfigs.count>0) {
        
        for (NSDictionary* dicc in funConfigs )
        {
            
            if ([[NSString stringWithFormat:@"%@",[dicc valueForKey:@"display"] ]isEqualToString:@"1"]&&[[NSString stringWithFormat:@"%@",[dicc valueForKey:@"funCode"]]isEqualToString:@"menu_booking_list"]){
                menu.items=nil;
                textArray=nil;
                imageArray=nil;
                menu.items = @[@{@"title":@"营销管理" },@{@"title":@"销售管理" },@{@"title":@"库存管理"},@{@"title":@"预约管理"}];
               
                textArray=[NSArray arrayWithObjects:@"扫码入会", @"会员管理",@"新媒体推广",@"下单收银",@"销售订单",@"提货配送",@"销售退货",@"要货订单",@"商品入库",@"商品出库",@"库存盘点",@"存货管理",@"调拨单",@"进货单",@"预约单",nil];
                
                imageArray=[NSArray arrayWithObjects: @"dianpuerweima",
                            
                            @"huiyuan",
                            @"xinmeitituiguang",
                            @"shouyin",
                            @"xiaoshoudingdan",
                            @"tihuopeisong",
                            @"xiaoshoutuihuo_new",
                            @"yaohuoguanli",
                            @"shangpinruku",
                            @"shangpinchuku",
                            @"kucunpandian",
                            @"cunhuoguanli",
                            @"diaobodan",
                            @"jinhuodan",
                            @"yuyuedan", nil];
            }
        }
    }
    
    
    [user setObject:menu.items forKey:@"itemsArray"];
    [user synchronize];
    [_sideSlipView setContentView:menu];
    [self.view addSubview:_sideSlipView];
    
    
    
    
    colorArray =[NSArray arrayWithObjects:[UIColor colorWithRed:31.00/255.0 green:65.00/255.0 blue:99.00/255.0 alpha:1],[UIColor colorWithRed:31.00/255.0 green:62.00/255.0 blue:107.00/255.0 alpha:1], [UIColor colorWithRed:31.00/255.0 green:92.00/255.0 blue:121.00/255.0 alpha:1],[UIColor colorWithRed:31.00/255.0 green:103.00/255.0 blue:86.00/255.0 alpha:1],[UIColor colorWithRed:64.00/255.0 green:95.00/255.0 blue:31.00/255.0 alpha:1],[UIColor colorWithRed:102.00/255.0 green:98.00/255.0 blue:31.00/255.0 alpha:1],[UIColor colorWithRed:100.00/255.0 green:31.00/255.0 blue:46.00/255.0 alpha:1],[UIColor colorWithRed:105.00/255.0 green:46.00/255.0 blue:31.00/255.0 alpha:1],nil];

    [self setAutolayOut];
    [self setUserSelectedDefault];
    
    
}
-(void)NewVersion{
  
    NSString *str1=[NSString stringWithFormat:@"%d",TARGET_VERSION];
    NSString *plistPath1 = [[NSBundle mainBundle] pathForResource:str1 ofType:@"plist"];
    NSDictionary *dictionary1 = [[NSDictionary alloc] initWithContentsOfFile:plistPath1];
    NSString *type = [dictionary1 objectForKey:@"type"];NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:type forKey:@"type"];
//    NSLog(@"param====%@",param);
    [HttpRequest requestData1:@"UpGrade/NewVersion" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
       
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
//                 NSLog(@"data====%@",severDataDict.dataDict);
                NSString *getVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
                NSString *VersionName = [NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"VersionName"]];

                NSArray *getVersionArray = [getVersion componentsSeparatedByString:@"."]; //从字符A中分隔成几个个元素的数组
                NSArray *VersionNameArray = [VersionName componentsSeparatedByString:@"."]; //从字符A中分隔成几个个元素的数组
               
                if ([getVersion isEqualToString:VersionName]) {
                    
                    }else{
                    if ([[NSString stringWithFormat:@"%@", [severDataDict.dataDict objectForKey:@"IsForce"]]isEqualToString:@"1"]) {
                       if (VersionNameArray.count==4) {
                          
                           
                    NSArray*getVersionArray1=@[[NSString stringWithFormat:@"%.f",[getVersionArray[0]doubleValue]*10000000],[NSString stringWithFormat:@"%.f",[getVersionArray[1]doubleValue]*100000],[NSString stringWithFormat:@"%.f",[getVersionArray[2]doubleValue]*1000],[NSString stringWithFormat:@"%.f",[getVersionArray[3]doubleValue]]];
//
                   NSArray*VersionNameArray1=@[[NSString stringWithFormat:@"%.f",[VersionNameArray[0]doubleValue]*10000000],[NSString stringWithFormat:@"%.f",[VersionNameArray[1]doubleValue]*100000],[NSString stringWithFormat:@"%.f",[VersionNameArray[2]doubleValue]*1000],[NSString stringWithFormat:@"%.f",[VersionNameArray[3]doubleValue]]];
                           

                           NSString*VersionNameStr=[VersionNameArray1 valueForKeyPath:@"@sum.floatValue"];
                           
                           NSString*getVersionStr=[getVersionArray1 valueForKeyPath:@"@sum.floatValue"];

                         NSLog(@"data====%@  %@",getVersionStr,VersionNameStr);
                        if (VersionNameStr.intValue>=getVersionStr.intValue) {
                            [Global hideProgressHUDInternal:self.view];
                            [Global showTextHudSub:[severDataDict.dataDict objectForKey:@"ResultString"] view:self.view];

                        }else{
                      
                        }
                       }
                    }else{
                        
                 }
                }
            
            }
            else{
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
                    [self.navigationController pushViewController:detailViewController animated:YES];
                }
                
            }
            
        }
        else
        {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:severDataDict.resultStr view:self.view];
        
        }
        
    }];
}

-(void)userInfo{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:@"有消息内容" forKey:@"Left"];
    [user synchronize];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        _dotLabel.hidden=NO;//红点提示
    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(userInfo) name:@"userInfo" object:Nil];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(NewVersion) name:@"NewVersion" object:Nil];
    self.navigationController.navigationBarHidden=YES;
    [[self rdv_tabBarController] setTabBarHidden:NO];
    commdity=[[ReabamSingleton shared]init];
    commdity.dataMemberDict=nil;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* tokenId = [user objectForKey:@"tokenId"];
    NSString* parent0 = [user objectForKey:@"parent0"];
    if (tokenId.length==0) {
        TheLoginViewController* Login=[[TheLoginViewController alloc]init];
        
        [self.navigationController pushViewController:Login animated:YES];
    }
    if ([[user objectForKey:@"userStatus"] isEqualToString:@"Y"]) {
        //通过后不需要加载
    }else{
        [[NSNotificationCenter defaultCenter]postNotificationName:@"changeTokenId" object:nil];//从新判断后台有木有通过；获取userStatus状态
    
    }
   
//获取消息数量
    int totalUnreadCount = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];
    if (totalUnreadCount>0) {
        _dotLabel.hidden=NO;
    }
    else if(totalUnreadCount==0)
    {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:@"已读" forKey:@"Left"];
        [user synchronize];
        _dotLabel.hidden=YES;
    }
    if ([[user objectForKey:@"Left"]isEqualToString:@"有消息内容"]) {
        _dotLabel.hidden=NO;

    }else{
        _dotLabel.hidden=YES;
    }
 
//更换帐号从新注册RongYunKey
    if ([[Global getRongYunToken] length]==0) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* Token = [user objectForKey:@"tokenId"];
        if (Token.length>0) {
            
            NSString *str1=[NSString stringWithFormat:@"%d",TARGET_VERSION];
            //     NSLog(@"str1111===%@",str1);
            NSString *plistPath1 = [[NSBundle mainBundle] pathForResource:str1
                                                                   ofType:@"plist"];
            NSDictionary *dictionary1 = [[NSDictionary alloc] initWithContentsOfFile:plistPath1];
            //    NSLog(@"dictionary1===%@",dictionary1);
            NSString *rongYunKey = [dictionary1 objectForKey:@"RongYunKey"];
            NSLog(@"rdvtabbar init rongyun key");
            [[RCIM sharedRCIM] initWithAppKey:rongYunKey];//设置容云appKEY
            [RCIM sharedRCIM].receiveMessageDelegate = self;
            [self RequestRongYunToken];
            
        }
        
    }
   
    
    
    
    if ([[NSString stringWithFormat:@"%@",parent0]length]==6) {
        
        isDefault=YES;
        [self menuView];
        
    }
    
    
}

-(void)RequestRongYunToken
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"user" forKey:@"userType"];
     NSLog(@"rToken====%@",param);
    [HttpRequest requestData:@"Chat/RegChat" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
    // NSLog(@"rToken====%@",severDataDict.dataDict);
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
    
                [[RCIM sharedRCIM] setConnectionStatusDelegate:self];
                NSString *  rongYunToken=[[severDataDict.dataDict objectForKey:@"chatInfo"] objectForKey:@"chatToken"];
                [Global setRongYunToken:rongYunToken];
           
                [[RCIM sharedRCIM] connectWithToken:rongYunToken success:^(NSString *userId) {
                [[RCIM sharedRCIM] setUserInfoDataSource:self];
                    
                    
                } error:^(RCConnectErrorCode status) {
                    NSLog(@"登陆的错误码为:%ld", (long)status);
                } tokenIncorrect:^{
                    NSLog(@"token错误");
                }];
            }
            else{
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
                    [self.navigationController pushViewController:detailViewController animated:YES];
                }
                
            }
            
        }
        else
        {
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            if ([[user objectForKey:@"userStatus"] isEqualToString:@"E"]) {
                [Global showTextHudSub:@"请认证门店！" view:self.view];
            }else{
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:severDataDict.resultStr view:self.view];
            }
        }
        
    }];
    
}
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status {
    //    NSLog(@"rdvtabbarstatus###^^^===%d",status);
}
- (void)getUserInfoWithUserId:(NSString *)userId
                   completion:(void(^)(RCUserInfo* userInfo))completion
{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:userId forKey:@"userId"];
       NSLog(@"getP=====%@",param);
    [HttpRequest requestData:@"Chat/GetChatUserInfo" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"getR=====%@",severDataDict.dataDict);
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                NSString * userNameStr=[[severDataDict.dataDict objectForKey:@"chatInfo"] objectForKey:@"chatUserName"];
                RCUserInfo *user = [[RCUserInfo alloc]init];
                user.userId =userId;
                user.name =userNameStr;
                user.portraitUri = [[severDataDict.dataDict objectForKey:@"chatInfo"] objectForKey:@"chatUserLogoUrl"];
                return completion(user);
            }
            else{
                }
            }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
            
        }
        
    }];
    
}
//自动读取容云当前后台返回时的数据
- (void)onRCIMReceiveMessage:(RCMessage *)message

                        left:(int)left
{
    int allunread = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];//获取消息数量
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:@"有消息内容" forKey:@"Left"];
    [user synchronize];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        _dotLabel.hidden=NO;//红点提示
    }];
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)//应用在前台
    {
        //修改app消息界面的参数
        }
    
    else//应用在后台
        
    {
        if(allunread > 0)
            
        {
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:allunread];//修改应用图标上的数字
            [UIApplication sharedApplication].applicationIconBadgeNumber = allunread;
        }
        
    }
    
}


-(void)setUserSelectedDefault
{
    
    [selectedTextArray removeAllObjects];
    [selectedImageArray removeAllObjects];
    for (UIView *v in _scrollView.subviews) {
        [v removeFromSuperview];
    }
    int selectedID=0;
    int m=0;
    
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    for ( int i=0; i<4; i++) {
        NSString *parentKeyStr= [NSString stringWithFormat:@"parent%ld",(long)i];
        if ([userDefaults dictionaryForKey:parentKeyStr]) {
            isDefault=NO;
        }
        NSMutableDictionary *dict=[NSMutableDictionary  dictionaryWithDictionary:[userDefaults dictionaryForKey:parentKeyStr]];
        NSMutableArray *array=[NSMutableArray arrayWithArray:[dict objectForKey:@"addOrSubtractARRAY"]];
        
        for (int j=0; j<array.count; j++) {
            
            if ([[array objectAtIndex:j]isEqualToString:@"Y"]) {
                
                selectedID=m;
                [selectedTextArray addObject:[textArray objectAtIndex:selectedID]];
                [selectedImageArray addObject:[imageArray objectAtIndex:selectedID]];
            }
            m++;
        }
    }
    
    //    NSLog(@"selectedTextArray===%@",selectedTextArray);
    //
    if (isDefault) {
        for (int i=0; i<defaultImageArray.count; i++) {
            [selectedTextArray addObject:[defaultTextArray objectAtIndex:i ]];
            [selectedImageArray addObject:[defaultImageArray objectAtIndex:i]];
        }
        
    }
    
    if (selectedTextArray.count==0)
    {
        
        UIButton *addButton=[UIButton buttonWithType:UIButtonTypeCustom];
        addButton.frame=CGRectMake(10, 93, ((ScreenWidth-25)/2), (ScreenHeight-187)/4);
        addButton.backgroundColor=[UIColor colorWithRed:240.0f/255.0f green:240.0f/255.0f blue:240.0f/255.0f alpha:1.0f];
        [addButton setImage:[UIImage imageNamed:@"datianjia_new.png"] withTitle:@"添加" forState:UIControlStateNormal];
        [addButton setTitleColor:[UIColor colorWithRed: 204.0/255.0f green:204.0/255.0f blue:204.0/255.0f alpha:1.0] forState:UIControlStateNormal];
        [addButton.layer setCornerRadius:6.0]; //设置矩圆角半径
        [addButton.layer setBorderWidth:0.3];   //边框宽度
        CGColorSpaceRef tureBTnSpace = CGColorSpaceCreateDeviceRGB();
        CGColorRef tureBTncolorref = CGColorCreate(tureBTnSpace,(CGFloat[]){255/255.0, 255/255.0, 255/255.0, 1.0});
        [addButton.layer setBorderColor:tureBTncolorref];//边框颜色
        [addButton addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_scrollView addSubview:addButton];
        [_scrollView setContentSize:CGSizeMake(0, addButton.frame.origin.y+ addButton.frame.size.height)];
        [_scrollView setScrollEnabled:YES];
        
    }
    
    else
    {
        for (int i=0; i<selectedTextArray.count; i++) {
            UIButton *selectedButton=[UIButton buttonWithType:UIButtonTypeCustom];
            selectedButton.frame=CGRectMake(10+(i%2)*((ScreenWidth-25)/2+5),93+ 5*(i/2)+(i/2)*(ScreenHeight-187)/4, ((ScreenWidth-25)/2), (ScreenHeight-187)/4);
            //        NSLog(@"(ScreenHeight-15-79-78)/4===%f",ScreenHeight);
            selectedButton.backgroundColor=colorArray[i%8];
            selectedButton.tag=i;
            // NSLog(@"width===%0.02f",selectedButton.frame.size.width);
            [selectedButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [selectedButton setImage:[UIImage imageNamed:[selectedImageArray objectAtIndex:i]] withTitle:[selectedTextArray objectAtIndex:i] forState:UIControlStateNormal];
            [selectedButton.layer setCornerRadius:6.0]; //设置矩圆角半径
            [selectedButton.layer setBorderWidth:0.3];   //边框宽度
            CGColorSpaceRef tureBTnSpace = CGColorSpaceCreateDeviceRGB();
            CGColorRef tureBTncolorref = CGColorCreate(tureBTnSpace,(CGFloat[]){255/255.0, 255/255.0, 255/255.0, 1.0});
            [selectedButton.layer setBorderColor:tureBTncolorref];//边框颜色
            
            [_scrollView addSubview:selectedButton];
            if (i==selectedTextArray.count-1) {
                UIButton *addButton=[UIButton buttonWithType:UIButtonTypeCustom];
                addButton.frame=CGRectMake(10+(selectedTextArray.count%2)*((ScreenWidth-25)/2+5), 93+5*(selectedTextArray.count/2)+(selectedTextArray.count/2)*(ScreenHeight-187)/4, ((ScreenWidth-25)/2), (ScreenHeight-187)/4);
                addButton.backgroundColor=[UIColor colorWithRed:240.0f/255.0f green:240.0f/255.0f blue:240.0f/255.0f alpha:1.0f];
                [addButton setImage:[UIImage imageNamed:@"datianjia_new.png"] withTitle:@"添加" forState:UIControlStateNormal];
                [addButton setTitleColor:[UIColor colorWithRed: 204.0/255.0f green:204.0/255.0f blue:204.0/255.0f alpha:1.0] forState:UIControlStateNormal];
                [addButton addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
                [addButton.layer setCornerRadius:6.0]; //设置矩圆角半径
                [addButton.layer setBorderWidth:0.3];   //边框宽度
                CGColorSpaceRef tureBTnSpace = CGColorSpaceCreateDeviceRGB();
                CGColorRef tureBTncolorref = CGColorCreate(tureBTnSpace,(CGFloat[]){255/255.0, 255/255.0, 255/255.0, 1.0});
                [addButton.layer setBorderColor:tureBTncolorref];//边框颜色
                [_scrollView addSubview:addButton];
                [_scrollView setContentSize:CGSizeMake(0, addButton.frame.origin.y+ addButton.frame.size.height +49)];
                [_scrollView setScrollEnabled:YES];
                
            }
        }
    }
}
-(void)btnClick:(UIButton *)sender
{
     NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"userStatus"] isEqualToString:@"E"]) {
        ToBindCompanyViewController * Login=[[ToBindCompanyViewController alloc]init];
        Login.viewSat=@"The original road";
        [self.navigationController pushViewController:Login animated:YES];
    }else if ([[user objectForKey:@"userStatus"] isEqualToString:@"W"]){
        [[self rdv_tabBarController] setSelectedIndex:4];//my
        
    }else{

    if (sliderIsOpen) {
        [_sideSlipView hide];
        sliderIsOpen=NO;
    }
    else
    {
        if (selectedTextArray.count>sender.tag) {
            
            NSString *str=[selectedTextArray objectAtIndex:sender.tag];
            
            NSInteger index=[textArray indexOfObject:str];
            
            NSString *vcStr=[viewControllerArray objectAtIndex:index];
            if ([vcStr isEqualToString:@"ActivityViewController"]) {
                [Global setType:@"Act"];
            }
            else if ([vcStr isEqualToString:@"PlaceOrderViewController"]) {
                [Global setType:@"PlaceOrder"];
                [Global setPlaceOrderPType:@"saleItem"];
                
            }
            else if ([vcStr isEqualToString:@"GenerateQRCodeViewController"])
            {
                [Global setType:@"GetCompanyQrCode"];
                
            }
            else if ([vcStr isEqualToString:@"CashierNewViewController"])
            {
                
                [Global setPlaceOrderPType:@"saleItem"];
                [Global setType:@"SCANCASHIER"];//收银
                [Global setScanTitle:@"扫收银"];

            }
            UIViewController * vc = (UIViewController*)[[NSClassFromString(vcStr) alloc] init];
            
            if (vc==nil) {
                UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"尚未开通" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
            }
            else
            {
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    }
    }
}

-(void)subTableviwAddOrSubtractClickAtHome
{
    
    [self setUserSelectedDefault];
}
- (void) didSelectCellAtChildIndex:(NSInteger)childIndex withInParentCellIndex:(NSInteger)parentIndex
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"userStatus"] isEqualToString:@"E"]) {
        ToBindCompanyViewController * Login=[[ToBindCompanyViewController alloc]init];
        Login.viewSat=@"The original road";
        [self.navigationController pushViewController:Login animated:YES];
    }else if ([[user objectForKey:@"userStatus"] isEqualToString:@"W"]){
     [[self rdv_tabBarController] setSelectedIndex:4];//my
    
    }else{
        NSArray *vcArray = [[NSArray alloc] initWithObjects:
                            [NSArray arrayWithObjects:@"GenerateQRCodeViewController",@"MemberListViewController",@"NewMediaPromotionViewController",nil],
                            [NSArray arrayWithObjects:@"CashierNewViewController", @"OrderListViewController", @"DeliverylistViewController",@"RefundListViewController",nil],
                           [NSArray arrayWithObjects:@"NeedOrderListViewController",@"WhsInListViewController",@"WhsOutListViewController",@"CheckVouchListViewController",@"StockManagementViewController",@"AllotOrderListViewController",@"GoodsInOrderListViewController", nil],
                            [NSArray arrayWithObjects:@"BookingOrderViewController",nil],
                            
                            nil];
        
    
    
    NSString *vcStr=[[vcArray objectAtIndex:parentIndex] objectAtIndex:childIndex];
    
    if ([vcStr isEqualToString:@"ActivityViewController"]) {
        [Global setType:@"Act"];
    }
    else if ([vcStr isEqualToString:@"PlaceOrderViewController"]) {
        [Global setType:@"PlaceOrder"];
        [Global setPlaceOrderPType:@"saleItem"];
    }
    else if ([vcStr isEqualToString:@"GenerateQRCodeViewController"])
    {
        [Global setType:@"GetCompanyQrCode"];
    }
    else if ([vcStr isEqualToString:@"CashierNewViewController"])
    {
        [Global setPlaceOrderPType:@"saleItem"];
        [Global setType:@"SCANCASHIER"];//收银
        [Global setScanTitle:@"扫收银"];
        
    }

    
    UIViewController * vc = (UIViewController*)[[NSClassFromString(vcStr) alloc] init];
    if (vc==nil) {
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"尚未开通" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        [_sideSlipView hide];
        sliderIsOpen=NO;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    }
}
-(void)hideSlider
{
    [[self rdv_tabBarController] setTabBarHidden:NO];
    _homeBtnView.hidden=YES;
    [_topView setBackgroundColor:[UIColor clearColor]];
    [UIView animateWithDuration:0.3 animations:^{
        [_contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left) ;
            make.width.equalTo(self.view.mas_width);
            make.bottom.equalTo(self.view.mas_bottom) ;
            make.top.equalTo(self.view.mas_top) ;
        }];
    } completion:^(BOOL finished) {
        
    }];
    
    
    sliderIsOpen=NO;
    
    
}
-(void)showSlider
{
    
    [_scrollView setContentOffset:CGPointMake(0, 0)];
    sliderIsOpen=YES;
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    _homeBtnView.hidden=YES;
    [_topView setBackgroundColor:[UIColor clearColor]];
    
    [_contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).with.offset(250);
        make.width.equalTo(self.view.mas_width);
        
        make.bottom.equalTo(self.view.mas_bottom) ;
        
        
        make.top.equalTo(self.view.mas_top) ;
    }];
    
    
}
-(void)menuViewHomeBtnClick
{
    sliderIsOpen=NO;
    [_sideSlipView hide];
}
-(void)menuViewConfirmCancelClick
{
    [_sideSlipView hide];
    TheLoginViewController* Login=[[TheLoginViewController alloc]init];
    
    [self.navigationController pushViewController:Login animated:YES];
    
}
- (IBAction)leftSliderBtnClick:(id)sender {
    
    if (sliderIsOpen) {
        [[self rdv_tabBarController] setTabBarHidden:NO];
        _homeBtnView.hidden=YES;
        [_topView setBackgroundColor:[UIColor clearColor]];
        [_sideSlipView hide];
        sliderIsOpen=NO;
        
        
    }
    else
    {
        [[self rdv_tabBarController] setTabBarHidden:YES];
        _homeBtnView.hidden=NO;
        [_scrollView setContentOffset:CGPointMake(0, 0)];
        [_topView setBackgroundColor:[UIColor whiteColor]];
        [_sideSlipView show];
        sliderIsOpen=YES;
        
    }
    // sliderIsOpen=!sliderIsOpen;
}
- (void)addBtnClick{
    if (sliderIsOpen) {
        [[self rdv_tabBarController] setTabBarHidden:NO];
        _homeBtnView.hidden=YES;
        [_topView setBackgroundColor:[UIColor clearColor]];
        [_sideSlipView hide];
        sliderIsOpen=NO;
        
    }
    else
    {
        
        [[self rdv_tabBarController] setTabBarHidden:YES];
        _homeBtnView.hidden=NO;
        [_scrollView setContentOffset:CGPointMake(0, 0)];
        [_topView setBackgroundColor:[UIColor whiteColor]];
        [_sideSlipView show];
        sliderIsOpen=YES;
        
    }
    
}

- (IBAction)messageBtnClick:(id)sender {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];//修改应用图标上的数字
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"userStatus"] isEqualToString:@"E"]) {
        ToBindCompanyViewController * Login=[[ToBindCompanyViewController alloc]init];
        Login.viewSat=@"The original road";
        [self.navigationController pushViewController:Login animated:YES];
    }else if ([[user objectForKey:@"userStatus"] isEqualToString:@"W"]){
        [[self rdv_tabBarController] setSelectedIndex:4];//my
        
    }else{
        MessageViewController *messageVC = [[MessageViewController alloc] init];
        [self.navigationController pushViewController:messageVC animated:YES];
    }
}
- (IBAction)scanBtnClick:(id)sender {
    //    ScanViewController *scanVC = [[ScanViewController alloc] init];
    //
    //    [self.navigationController pushViewController:scanVC animated:YES];
}
-(void)setAutolayOut
{
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.width.equalTo(self.view.mas_width);
        
        //   make.bottom.equalTo(self.view.mas_bottom).with.offset(-[[[self rdv_tabBarController] tabBar] height]) ;
        
        make.bottom.equalTo(self.view.mas_bottom);
        make.top.equalTo(self.view.mas_top) ;
    }];
    
    [_homeBtnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        
        make.bottom.equalTo(self.view.mas_bottom);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@49);
        make.width.equalTo(_contentView.mas_width);
        
    }];
    
    [_homeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_homeBtnView.mas_left).with.offset(10) ;
        
        make.bottom.equalTo(_homeBtnView.mas_bottom);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@49);
        make.width.equalTo(_contentView.mas_width).dividedBy(5);
        
    }];
    [_zhanTingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_homeBtn.mas_right)  ;
        
        make.bottom.equalTo(_homeBtnView.mas_bottom);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@49);
        make.width.equalTo(_contentView.mas_width).dividedBy(5);
        
    }];
    
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_contentView.mas_left);
        make.width.equalTo(_contentView.mas_width);
        
        make.height.equalTo(@93);
        make.top.equalTo(_contentView.mas_top) ;
    }];
    
    [_leftSliderBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_contentView.mas_left).with.offset(5);
        
        make.top.equalTo(_contentView.mas_top).with.offset(41.5);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@30);
        make.width.equalTo(@40);
        
    }];
    
    [_messageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        // make.left.equalTo(_scanBtn.mas_right).with.offset(10);
        make.right.equalTo(_contentView.mas_right).with.offset(-10);
        make.top.equalTo(_contentView.mas_top).with.offset(41.5);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@30);
        make.width.equalTo(@40);
        
    }];
    [_dotLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(_contentView.mas_right).with.offset(-12);
        make.top.equalTo(_contentView.mas_top).with.offset(45.5);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@8);
        make.width.equalTo(@8);
        
    }];
    
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_contentView.mas_left);
        make.width.equalTo(_contentView.mas_width);
        make.top.equalTo(_contentView.mas_top)  ;
        make.bottom.equalTo(_contentView.mas_bottom);
    }];
    
}


@end
